package com.fastCms.manager.bim.controller.api;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.fastCms.business.bim.enums.ReportTypeEnum;
import com.fastCms.business.bim.manage.WordManageService;
import com.fastCms.business.bim.plugins.excel.ExcelUtil;
import com.fastCms.business.bim.plugins.word.NewWordUtils;
import com.fastCms.business.bim.pojo.excel.FootReportExcel;
import com.fastCms.business.bim.pojo.excel.PfReportExcel;
import com.fastCms.business.bim.pojo.vo.CarbonEmissionVO;
import com.fastCms.business.bim.pojo.vo.CarbonFootprintVO;
import com.fastCms.business.bim.pojo.vo.ImportReportListVO;
import com.fastCms.business.bim.pojo.vo.ReportSerialNoVO;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.utils.opc.DateUtil;
import com.fastCms.manager.frame.annotation.UserAccess;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("api/word")
@Api(value = "ApiWordController", tags = "前台-word导出")
@UserAccess
@Log4j2
@CrossOrigin(origins = "*")
public class ApiWordController {

    @Autowired
    private WordManageService wordManageServiceImpl;


    @ApiOperation(value = "获取企业信息", notes = "")
    @GetMapping("/getCompany")
    public ApiResponse<CarbonFootprintVO.Company> getCompany() {
        CarbonFootprintVO.Company company = wordManageServiceImpl.getCompany();
        return ResponseUtil.success(company);
    }

    @ApiOperation(value = "保存企业信息", notes = "")
    @PostMapping("/saveCompany")
    public ApiResponse<Boolean> saveCompany(@RequestBody CarbonFootprintVO.Company company) {
        Boolean result = wordManageServiceImpl.saveCompany(company);
        return ResponseUtil.success(result);
    }


    //----------------------- 碳排放 ↓ ---------------------------
    @ApiOperation(value = "碳排放数据-下载模版", notes = "")
    @GetMapping("/downloadPfTemp")
    public ApiResponse<Boolean> downloadPfTemp() {
        return ResponseUtil.success("https://app-1318386832.cos.ap-nanjing.myqcloud.com/system/lib/tpf-temp-new.xlsx");
    }

    @ApiOperation(value = "碳排放数据-导入", notes = "")
    @PostMapping("/importPf")
    public ApiResponse<Boolean> importPf(@RequestParam("multipartFile") MultipartFile multipartFile) {
        try {
            ExcelUtil<PfReportExcel> util = new ExcelUtil<>(PfReportExcel.class);
            List<PfReportExcel> userList = util.importExcel(multipartFile.getInputStream());
            wordManageServiceImpl.importPf(userList);
            return ResponseUtil.success(true);
        } catch (Exception e) {
            return ResponseUtil.fail("模板错误，建议下载最新模板填充数据");
        }
    }

    @ApiOperation(value = "碳排放数据-历史列表", notes = "")
    @PostMapping("/importPfList")
    public ApiResponse<List<ImportReportListVO>> importPfList() {
        List<ImportReportListVO> result = wordManageServiceImpl.importReportList(ReportTypeEnum.TPF.getType());
        return ResponseUtil.success(result);
    }

    @ApiOperation(value = "碳排放数据-导出", notes = "")
    @GetMapping("/export/carbonEmission")
    public void exportCarbonEmission(@RequestParam("serialNo") String serialNo, HttpServletRequest request, HttpServletResponse response) {
        CarbonEmissionVO reportData = wordManageServiceImpl.exportCarbonEmission(serialNo);
        try {
            Map<String, Object> resultMap = BeanUtil.beanToMap(reportData, false, false);
            String generateWordName = URLEncoder.encode("实验室碳排放报告" + "-" + DateUtil.getCurrentDay(), "UTF-8") + ".doc";
            NewWordUtils.exportMillCertificateWord(request, response, resultMap, "3132.ftl", generateWordName, "word");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException("导出异常，请稍后重试");
        }
    }

    //----------------------- 碳排放 ↑ ---------------------------

    @ApiOperation(value = "通用-删除", notes = "碳排放和碳足迹通用")
    @PostMapping("/delete")
    public ApiResponse<Boolean> delete(@RequestBody ReportSerialNoVO reportSerialNo) {
        Boolean result = wordManageServiceImpl.delete(reportSerialNo.getSerialNo());
        return ResponseUtil.success(result);
    }

    //----------------------- 碳足迹 ↓ ---------------------------
    @ApiOperation(value = "碳足迹数据-下载模版", notes = "")
    @GetMapping("/downloadFootTemp")
    public ApiResponse<Boolean> downloadFootTemp() {
        return ResponseUtil.success("https://app-1318386832.cos.ap-nanjing.myqcloud.com/system/lib/tzj-temp-new.xlsx");
    }

    @ApiOperation(value = "碳足迹数据-导入", notes = "")
    @PostMapping("/importFoot")
    public ApiResponse<Boolean> importFoot(@RequestParam("multipartFile") MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        if (!"xlsx".equals(Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".") + 1))) {
            return ResponseUtil.fail("文件类型错误");
        }
        try {
            ExcelUtil<FootReportExcel> util = new ExcelUtil<>(FootReportExcel.class);
            List<FootReportExcel> userList = util.importExcel(multipartFile.getInputStream());
            wordManageServiceImpl.importFoot(userList);
            return ResponseUtil.success(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseUtil.fail("模板错误，建议下载最新模板填充数据");
        }
    }

    @ApiOperation(value = "碳足迹数据-历史列表", notes = "")
    @PostMapping("/importFootList")
    public ApiResponse<List<ImportReportListVO>> exportFootList() {
        List<ImportReportListVO> result = wordManageServiceImpl.importReportList(ReportTypeEnum.TZJ.getType());
        return ResponseUtil.success(result);
    }

    @ApiOperation(value = "碳足迹数据-导出", notes = "")
    @GetMapping("/export/carbonFootprint")
    public void exportCarbonFootprint(@RequestParam("serialNo") String serialNo, HttpServletRequest request, HttpServletResponse response) {
        CarbonFootprintVO reportData = wordManageServiceImpl.exportCarbonFootprint(serialNo);
        try {
            Map<String, Object> resultMap = BeanUtil.beanToMap(reportData, false, false);
            String generateWordName = URLEncoder.encode("实验室设备碳足迹报告" + "-" + DateUtil.getCurrentDay(), "UTF-8") + ".doc";
            NewWordUtils.exportMillCertificateWord(request, response, resultMap, "0326-1.ftl", generateWordName, "word");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ApiException("导出异常，请稍后重试");
        }
    }

    //----------------------- 碳足迹 ↑ ---------------------------

//    @ApiOperation(value = "调试", notes = "")
//    @GetMapping("/export/test")
//    public void test(HttpServletRequest request, HttpServletResponse response) {
//        TestVO testVO = new TestVO();
//        testVO.setTestContent("你好!");
//        try {
//            Map<String, Object> resultMap = BeanUtil.beanToMap(testVO, false, false);
//            String generateWordName = URLEncoder.encode("调试word" + "-" + DateUtil.getCurrentDay(), "UTF-8") + ".docx";
//            NewWordUtils.exportMillCertificateWord(request, response, resultMap, "test.ftl", generateWordName, "word");
//        } catch (Exception e) {
//            throw new ApiException("导出异常，请稍后重试");
//        }
//    }

    public static void main(String[] args) {
        Object val = 12;
        if ((Double) val % 1 > 0) {
            val = new DecimalFormat("0.00").format(val);
        } else {
            val = new DecimalFormat("0").format(val);
        }
        System.out.println(val);
    }

}
